package com.rc.saas.mini.service;

import com.github.pagehelper.util.StringUtil;

import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.common.enums.ElecPileStopReasonEnum;
import com.rc.saas.mini.common.utils.DateHelper;
import com.rc.saas.mini.model.elec.ElecGun;
import com.rc.saas.mini.model.elec.ElecStation;
import com.rc.saas.mini.model.member.MemberAccount;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.tenant.Tenant;
import com.rc.saas.mini.model.tenant.TenantWeixinTemplate;
import com.rc.saas.mini.service.elec.ElecGunService;
import com.rc.saas.mini.service.elec.ElecStationService;
import com.rc.saas.mini.service.member.MemberAccountService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.tenant.TenantService;
import com.rc.saas.mini.service.tenant.TenantWeixinTemplateService;
import com.rc.saas.mini.vo.charge.CommandStartReq;
import com.rc.saas.mini.vo.charge.CommandStopReq;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.weixin4j.miniprogram.WeixinMiniprogram;
import org.weixin4j.miniprogram.component.SubscribeMessageComponent;
import org.weixin4j.miniprogram.model.template.message.TemplateMessageData;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class MiniSubscribeService {

    private static Logger logger = LogManager.getLogger(MiniSubscribeService.class);

    @Autowired
    private TenantService tenantService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private TenantWeixinTemplateService tenantWenxinTemplateSevice;

    //
    //@Value("${weChat.url}")
    //private String weChatUrl;

    public int notification_stationsStatus(String connectorID) {
        return 0;
    }

    public int notification_start_charge_result(CommandStartReq commandStartReq) {
        return 0;
    }

    public TResponse notification_stop_charge_result(CommandStopReq commandStopReq) {
        final String msgTitle = "充电结束通知";
        TenantWeixinTemplate tenantWeixinTemplate = tenantWenxinTemplateSevice.selectByTemplateTitlea(commandStopReq.getTenantCode(), msgTitle);

        if (tenantWeixinTemplate == null || StringUtils.isBlank(tenantWeixinTemplate.getMsgNotifyUrl())) {
            logger.error(commandStopReq.getTenantCode() + ":找不到微信推送模板,:{},:{}", commandStopReq.getTenantCode(), msgTitle);
            return TResponse.FAIL("找不到微信推送模板");
        }

        String URL = tenantWeixinTemplate.getMsgNotifyUrl();
        //String URL = "https://saastest.jin-zhuang.cn/jinzhuang-saas-wechat/charge/sendFinishMsg";
        logger.info(commandStopReq.getTenantCode() + ":准备推送模板消息,:{},:{},:{}", commandStopReq.getTenantCode(), msgTitle, URL);

        OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(commandStopReq.getOrderId());
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(orderInfo.getMemberId());

        if (StringUtil.isEmpty(memberInfo.getMinipOpenid())) {
            return TResponse.FAIL("没有绑定openID");
        }


        //模板内容，不填则下发空模板
        List<TemplateMessageData> datas = new ArrayList<>();

        ElecStation elecStation = elecStationService.selectByPrimaryKey(orderInfo.getElecStationId());

        TemplateMessageData templateMessageData1 = new TemplateMessageData();
        templateMessageData1.setKey("thing2");
        templateMessageData1.setValue(elecStation.getStationName()); //充电站名称

        ElecGun elecGun = elecGunService.selectByPrimaryKey(orderInfo.getElecGunId());
        TemplateMessageData templateMessageData2 = new TemplateMessageData();
        templateMessageData2.setKey("time5");
        templateMessageData2.setValue(DateHelper.dataToString(orderInfo.getEndTime(), DateHelper.DATE_COMMON_FORMAT));//结束时间

        TemplateMessageData templateMessageData3 = new TemplateMessageData();
        templateMessageData3.setKey("amount8");
        templateMessageData3.setValue(String.valueOf(orderInfo.getPayAmount()));//消费金额


        MemberAccount memberAccount = memberAccountService.selectByMemberId(orderInfo.getTenantCode(), orderInfo.getMemberId());
        BigDecimal account = memberAccount.getAccount().add(memberAccount.getEnterpriseAccount());
        TemplateMessageData templateMessageData4 = new TemplateMessageData();
        templateMessageData4.setKey("amount14");
        templateMessageData4.setValue(String.valueOf(account));//账户余额

//        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
//        formatter.setTimeZone(TimeZone.getTimeZone("GMT+0"));
//        Date date = new Date(System.currentTimeMillis() - orderInfo.getStartTime().getTime());


        TemplateMessageData templateMessageData5 = new TemplateMessageData();
        templateMessageData5.setKey("thing11");
        templateMessageData5.setValue(ElecPileStopReasonEnum.getElecPileStopReasonResult(orderInfo.getPileStopReason().toString()));//停止方式


        //放入模板内容列表中
        datas.add(templateMessageData1);
        datas.add(templateMessageData2);
        datas.add(templateMessageData3);
        datas.add(templateMessageData4);
        datas.add(templateMessageData5);

        //获取小程序模板ID
//        TenantWeixinTemplate tenantWeixinTemplate = tenantWeixinTemplateService.selectByTemplateTitlea(memberInfo.getTenantCode(), "小程序充电结束通知");
        //跳转小程序页面路径
        String page = "/pages/powerEnd/powerEnd?orderId=" + orderInfo.getOrderId();
        //String page = "/pages/powerEnd/powerEnd?outOrderNum=" + orderInfo.getOrderId();

        try {
            Tenant tenant = tenantService.selectByPrimaryKey(memberInfo.getTenantCode());
            //获取微信小程序配置：
            WeixinMiniprogram weixinMiniprogram = new WeixinMiniprogram(tenant.getMinipAppid(), tenant.getMinipSecret());
            //添加订阅消息组件
            SubscribeMessageComponent subscribeMessage = new SubscribeMessageComponent(weixinMiniprogram);
            //推送订阅消息
            subscribeMessage.send(memberInfo.getMinipOpenid(), tenantWeixinTemplate.getWeixinTemplateId(), datas, page, tenantWeixinTemplate.getMiniProgramState());


            return TResponse.SUCCESS();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //}


        return TResponse.FAIL();
    }
}
